//
//  DialogCells.swift
//  BWPanelKit
//
//  Created by zhuxuhong on 2022/2/24.
//

import BWListKit
import BWUIKit

class DialogSeparatorCell: CollectionViewCell {
    override func didInit() {
        isUserInteractionEnabled = false
        contentView.backgroundColor = Dialog.appearance.separator.color
    }
}

class DialogActionCell: DialogTextCell {
    override func touchBegan(touch: UITouch) {
        contentView.backgroundColor = Dialog.appearance.separator.color
    }
    override func touchEnded(touch: UITouch) {
        contentView.backgroundColor = Dialog.appearance.contentView.backgroundColor
    }
    override func touchMoved(touch: UITouch) {
        touchBegan(touch: touch)
    }
    override func touchCancelled(touch: UITouch) {
        touchBegan(touch: touch)
    }
    
    override func didInit() {
        super.didInit()
        
        isUserInteractionEnabled = true
    }
    
    override func bwListItemViewConfigure(_ data: Any?, indexPath: IndexPath) {
        guard let action = data as? Dialog.Action else {
            return
        }
        touchEnded(touch: .init())
        label.text = action.title
        Self.config(label: label, text: action.title, config: action.style.config)
    }
}

class DialogTextCell: CollectionViewCell {
    lazy var label: UILabel = {
        let v = UILabel()
        v.frame = self.contentView.bounds
        v.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        return v
    }()
    
    public override func didInit() {
        isUserInteractionEnabled = false
        contentView.backgroundColor = Dialog.appearance.contentView.backgroundColor
        contentView.addSubview(label)
    }
    
    static func calculatedHeight(width: CGFloat, data: Dialog.Text) -> CGFloat
    {
        let label = UILabel()
        config(label: label, text: data.string, config: data.config)
        
        return label.sizeThatFits(.init(width: width, height: .greatestFiniteMagnitude)).height
    }
    
    static func config(label: UILabel, text: String?, config: Dialog.Text.Config) {
        label.textColor = config.color
        label.font = config.font
        label.textAlignment = config.alignment
        label.numberOfLines = config.numberOfLines
        
        if let text = text,
           let m = config.lineHeightMultiple
        {
            let pg = NSMutableParagraphStyle()
            pg.lineHeightMultiple = m
            pg.alignment = config.alignment
            label.attributedText = .init(string: text, attributes: [
                NSAttributedString.Key.paragraphStyle: pg
            ])
        }
        else {
            label.text = text
        }
    }
    
    override func bwListItemViewConfigure(_ data: Any?, indexPath: IndexPath) {
        guard let data = data as? Dialog.Text else {
            return
        }
        Self.config(label: label, text: data.string, config: data.config)
    }
}
